import Vue from 'vue'
import Router from 'vue-router'
import store from "@/store";
import api from "@/api/api";
import Login from '@/views/base/Login'
import Home from '@/views/base/Home'
import NoFound from '@/views/base/404'

Vue.use(Router)

const router = new Router({
  // routes[0]必须为'/'
  routes: [
    {path: '/', name: 'home', component: Home, needLogin: true, children: []},
    {path: '/login', name: 'login', component: Login, needLogin: false},
    {path: '*', name: '404', component: NoFound, needLogin: false},
  ]
})
// 导航守卫
router.beforeEach((to, from, next) => {
  let accountInfo = sessionStorage.getItem("accountInfo");
  if (to.path == '/login' && !to.needLogin) {
    if (accountInfo) {
      next({path: '/'})
    } else {
      next()
    }
  } else {
    if (!accountInfo) {
      next({
        path: '/login',
        query: {redirect: to.path}
      })
    } else{
      addDynamicMenuAndRoutes(accountInfo, to, from)
      next()
    }
  }
})


/**
 * 加载动态菜单和路由
 */
function addDynamicMenuAndRoutes(accountInfo, to, from) {
  if (store.state.app.menuRouteLoaded) {
    console.log('动态菜单和路由已经存在.')
    return
  }
  api.menu.findNavTree({'userId': accountInfo.id})
    .then(res => {
      // 添加动态路由
      let dynamicRoutes = addDynamicRoutes(res.data)
      router.options.routes[0].children = router.options.routes[0].children = dynamicRoutes;
      console.log(router.options.routes)
      router.addRoutes(router.options.routes)
      // 保存加载状态
      store.commit('menuRouteLoaded', true)
      // 保存菜单树
      store.commit('setNavTree', res.data)
    }).then(res => {
    // api.user.findPermissions({'name': accountInfo}).then(res => {
    //   // 保存用户权限标识集合
    //   store.commit('setPerms', res.data)
    // })
  })
    .catch(function (res) {
    })
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function addDynamicRoutes(menuList = [], routes = []) {
  var temp = [],isMounted = [];
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].children && menuList[i].children.length >= 1) {
      temp = temp.concat(menuList[i].children)
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, '')
      // 创建路由配置
      var query = GetRequest(menuList[i].url),
        path = (menuList[i].url.indexOf('?') > -1) ? menuList[i].url.substring(0, menuList[i].url.indexOf("?")) : menuList[i].url;
      if(isMounted.indexOf(path)==-1){
        isMounted.push(path)
        var route = {
          path: path,
          component: null,
          name: menuList[i].name,
          query:query,
          meta: {
            icon: menuList[i].icon,
            index: menuList[i].id
          }
        }
        try {
          // 根据菜单URL动态加载vue组件，这里要求vue组件须按照url路径存储
          let array = menuList[i].url.split('/')
          let url = ''
          for (let i = 0; i < array.length; i++) {
            url += array[i].substring(0, 1).toUpperCase() + array[i].substring(1) + '/'
          }
          url = url.substring(0, url.length - 1)
          let component = (url && url.indexOf('?') > -1) ? url.substring(0, url.indexOf("?")) : url
          route['component'] = resolve => require([`@/views/${component}`], resolve)
        } catch (e) {
        }
        routes.push(route)
      }
    }
  }
  if (temp.length >= 1) {
    addDynamicRoutes(temp, routes)
  } else {
    console.log('动态路由加载...')
    console.log(routes)
    console.log('动态路由加载完成.')
  }
  return routes
}

function GetRequest(url){
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(url.indexOf("?")+1,url.length),
    strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
  }
  return theRequest;
}

export default router;
